package cn.schoolwow.util.module.check.instanceList.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;

import java.util.Collection;
import java.util.List;

public class CheckInstanceListInValueListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String fieldName = (String) flowContext.getData("fieldName");
        List allowValueList = (List) flowContext.getData("allowValueList");
        List list = (List) flowContext.checkData("list");
        String message = (String) flowContext.checkData("message");

        if(null==fieldName||fieldName.isEmpty()){
            throw new IllegalArgumentException(message+"的字段名不能为空");
        }
        if(null==allowValueList||allowValueList.isEmpty()){
            throw new IllegalArgumentException(message+"允许值列表不能为空");
        }

        for(Object instance:list){
            Object fieldValue = QueryInstance.newQuery(instance)
                    .execute()
                    .getSingleFieldValue(fieldName);
            if(fieldValue instanceof Collection){
                Collection collection = (Collection) fieldValue;
                for(Object singleCollectionValue:collection){
                    if(!allowValueList.contains(singleCollectionValue)){
                        throw new IllegalArgumentException(message+"的值不合法!当前值:["+singleCollectionValue+"],允许值列表:"+allowValueList);
                    }
                }
            }else{
                if(!allowValueList.contains(fieldValue)){
                    throw new IllegalArgumentException(message+"的值不合法!当前值:["+fieldValue+"],允许值列表:"+allowValueList);
                }
            }
        }
    }

    @Override
    public String name() {
        return "实例列表-检查字段值是否在指定列表中";
    }
}
